package com.lanou.demo.backgrounddemo.service.impl;

import com.lanou.demo.backgrounddemo.mapper.ContentCategoryMapper;
import com.lanou.demo.backgrounddemo.service.ContentCategoryService;
import com.lanou.entity.entity.ContentCategoryEntity;
import com.lanou.entity.entity.TreeEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 常宏盛
 * Date: 2019/7/12 14:49
 **/
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {

    @Resource
    private ContentCategoryMapper contentCategoryMapper;

    @Override
    public List<TreeEntity> list(Long parentId) {
        List<ContentCategoryEntity> categoryList = this.contentCategoryMapper.list(parentId);
        if (categoryList.size() == 0) {
            return new ArrayList<>();
        }
        List<TreeEntity> treeList = new ArrayList<>();
        for (ContentCategoryEntity contentCategory : categoryList) {
            treeList.add(TreeEntity.builder()
                    .id(contentCategory.getId())
                    .text(contentCategory.getName())
                    .state(contentCategory.getIsParent() == 1 ? "closed" : "open")
                    .build());
        }
        return treeList;
    }

    @Override
    public int create(ContentCategoryEntity contentCategory) {
        int result = this.contentCategoryMapper.updateIsParentEqualsOne(contentCategory.getParentId());
        if (result == 0) {
            return 0;
        }
        this.contentCategoryMapper.create(contentCategory);
        return 1;
    }

    @Override
    public void update(Long id, String name) {
        this.contentCategoryMapper.update(id, name);
    }

    @Override
    public void delete(Long id) {
        this.contentCategoryMapper.delete(id);
        Long parentId = this.contentCategoryMapper.selectParentIdById(id);
        int count = this.contentCategoryMapper.selectParentIdCount(parentId);
        if (count == 0) {
            this.contentCategoryMapper.updateIsParentEqualsZero(parentId);
        }
    }

}

